import store from '@/utils/store'
import type { RouteLocationNormalizedGeneric, Router } from 'vue-router'

class Guard {
  constructor(private router: Router) {}
  public run() {
    this.router.beforeEach((to) => {
      const token = store.get('token')
      if (!this.isLogin(to, token)) return { name: 'login' }
    })
  }

  private isLogin(to: RouteLocationNormalizedGeneric, token: string) {
    return token || to.name === 'login' || to.name === 'register'
  }

  private isRegister(to: RouteLocationNormalizedGeneric) {
    if (to.name === 'register') return true
    return false
  }
}

export default (router: Router) => {
  new Guard(router).run()
}
